export default {
    PutSnippet(snippet) {
        if (snippet._id) {
            const id = snippet._id;
            delete snippet._id;
            delete snippet._openid;
            // set 方式不会更新？，是腾讯云的 BUG
            return this.db.collection("code-snippets").doc(id).update(snippet);
        } else {
            return this.db.collection("code-snippets").add(snippet);
        }
    },
    refreshSnippet(id) {
        return this.db
            .collection("code-snippets")
            .doc(id)
            .get()
            .then((res) => res.data);
    },
    deleteSnippet(id) {
        return this.db.collection("code-snippets").doc(id).remove();
    },
    async querySnippets(index, num = 10) {
        const querying = await this.db.collection("code-snippets").where({
            isPublic: true,
        });
        return querying
            .skip(index * num)
            .limit(10)
            .get()
            .then((res) => res.data);
    },
    async searchSnippets({ text }) {
        const _ = this.db.command;
        const reg = new RegExp(text, "gi");
        return this.db
            .collection("code-snippets")
            .where(
                _.or([
                    {
                        title: reg,
                    },
                    {
                        description: reg,
                    },
                ])
            )
            .get()
            .then((res) => {
                return res.data;
            });
    },
};
